<template>
  <view class="cu-modal bottom-modal" :class="show ? 'show' : ''" @tap="hide">
    <view class="cu-dialog" @tap.stop>
      <view class="cu-bar bg-white">
        <view class="action text-blue" @tap="clearCart">清空购物车</view>
        <view class="action" @tap="hide">
          <text class="cuIcon-close text-red"></text>
        </view>
      </view>
      <view class="cart-list padding-xl">
        <view v-if="Object.keys(cart).length === 0" class="text-center text-gray">购物车是空的</view>
        <view v-else>
          <view class="cart-item" v-for="(item, key) in cart" :key="key">
            <image :src="item.goods.img" class="goods-img"></image>
            <view class="goods-info">
              <view class="text-bold">{{ getComboInfo(item, 'comDescription') || item.goods.name }}</view>
              <view class="text-sm text-gray">{{ getComboInfo(item, 'specValues') }}</view>
            </view>
            <view class="price-stepper">
              <view class="price text-red text-bold">¥{{ getComboInfo(item, 'comPrice') || item.price || item.goods.price }}</view>
              <view class="stepper">
                <button class="cu-btn round sm icon" @click.stop="onMinus(key)">
                  <text class="cuIcon-move"></text>
                </button>
                <text class="count">{{ item.quantity }}</text>
                <button class="cu-btn round sm icon bg-yellow" @click.stop="onPlus(key)">
                  <text class="cuIcon-add"></text>
                </button>
              </view>
            </view>
          </view>
          
          <!-- 卡券/折扣区域 -->
          <view class="coupon-section">
            <text class="text-grey">到手约:</text>
            <text class="text-red">-¥{{ totalPrice }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { defineProps, defineEmits, computed, watch } from 'vue';
import { get, post } from '@/utils/request';


const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  cart: {
    type: Object,
    default: () => ({})
  },
  merchantId:{
    type:Number,
    default:null
  }
});

const emit = defineEmits(['update:cart', 'hide', 'update:totalPrice']);

// 计算总价格
const totalPrice = computed(() => {
  return Object.values(props.cart)
    .reduce((sum, item) => {
      const price = (item.comboInfo && item.comboInfo.length > 0 && item.comboInfo[0].comPrice !== undefined)
        ? item.comboInfo[0].comPrice
        : (item.price ?? item.goods.price);
      return sum + (price * item.quantity);
    }, 0)
    .toFixed(2);
});

// 监听总价变化并通知父组件
watch(totalPrice, (newPrice) => {
  emit('update:totalPrice', newPrice);
  submitCart();
});

const getComboInfo = (item, key) => {
  if (item.comboInfo && item.comboInfo.length > 0) {
    return item.comboInfo[0][key];
  }
  // 如果没有comboInfo且请求的是价格，则返回item.price备用
  if (key === 'comPrice' && item.price !== undefined) {
    return item.price;
  }
  return null;
};

const hide = () => {
  emit('hide');
};

const clearCart = () => {
  const newCart = {};
  emit('update:cart', newCart);
};

const onMinus = async (key) => {
  const newCart = { ...props.cart };
  const item = newCart[key];

  if (item) {
    try {
      const userData = uni.getStorageSync('user');
      const user = JSON.parse(userData);
      const userId = user.userId;
      const merchantId = props.merchantId;
      const goodId = item.goods.id;

      if (userId && merchantId && goodId) {
        // 诊断日志：打印将要发送的参数
        console.log('[Debug] Calling /cart/delete with params:', { userId, merchantId, goodId });
        
        // 手动拼接URL，确保格式正确
        const url = `/cart/delete?userId=${userId}&merchantId=${merchantId}&goodId=${goodId}`;
        
        // 调用接口，不再传递参数对象
        await get(url);

      } else {
        // 如果因为某些原因参数不全，也打印出来
        console.warn('[Debug] Skipped /cart/delete call due to missing params:', { userId, merchantId, goodId });
      }
    } catch (error) {
      console.error('调用删除接口失败:', error);
      // 即使删除失败，也继续前端操作，但给一个提示
      uni.showToast({ title: '同步删除失败', icon: 'none' });
    }

    // 然后正常处理前端的数量变化
    item.quantity--;
    if (item.quantity <= 0) {
      delete newCart[key];
    }
  }

  emit('update:cart', newCart);
};

const onPlus = (key) => {
  const newCart = { ...props.cart };
  if (newCart[key]) {
    newCart[key].quantity++;
  }
  emit('update:cart', newCart);
};

// 添加提交购物车方法
const submitCart = async () => {
  try {
    const userData = uni.getStorageSync('user');
    const user = JSON.parse(userData);
    const userId = user.userId;
    console.log("用户ID", userId);
     
    for (const key in props.cart) {
      const item = props.cart[key];
      const specsArray = JSON.parse(JSON.stringify(item.selectedSpecs || []))
      specsArray.forEach(spec => {
        console.log('spe的id',spec.spe_id)
        console.log('val的id',spec.val_id)
      });

      // 正确获取商品价格：优先使用套餐价格，其次使用商品原价
      const price = (item.comboInfo && item.comboInfo.length > 0 && item.comboInfo[0].comPrice !== undefined)
        ? item.comboInfo[0].comPrice
        : (item.price ?? item.goods.price);
      
      const cartItem = {
        userId,
        merchantId: props.merchantId,
        goodsId: item.goods.id, 
        goodNum: item.quantity,
        specs: specsArray,
        price: price            
      };
      
      console.log("正在同步的购物车项目:",cartItem)
      await post('/cart/addGood', cartItem);
    }
    
    // uni.showToast({ title: '购物车已同步', icon: 'none' });
  } catch (error) {
    console.error('同步购物车失败:', error);
    uni.showToast({ title: '同步失败', icon: 'none' });
  }

};
</script>

<style scoped>
.cart-list {
  max-height: 60vh;
  overflow-y: auto;
}
.cart-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f1f1f1;
}
.goods-img {
  width: 120rpx;
  height: 120rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
  flex-shrink: 0;
}
.goods-info {
  flex: 1;
  min-width: 0;
}
.price-stepper {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}
.price {
  margin-bottom: 10rpx;
}
.stepper {
  display: flex;
  align-items: center;
}
.stepper .count {
  margin: 0 20rpx;
  font-size: 32rpx;
}
.coupon-section {
    display: flex;
    justify-content: space-between;
    padding: 20rpx 0;
    margin-top: 20rpx;
    border-top: 1rpx solid #f1f1f1;
}
</style> 
